package com.qingzhuge.file.service.cloud;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import com.qingzhuge.exception.ServiceException;
import com.qingzhuge.file.entity.FileStorageConfig;
import com.qingzhuge.file.service.BaseFileStorageService;
import org.apache.commons.lang3.StringUtils;

import java.io.*;

/**
 * @author : zero.xiao
 * @description : 阿里云存储
 * @date :2018/6/8 0008 下午 15:13
 * @modified :
 * @since : 1.0.0
 */
public class StorageAliyunCloudService extends BaseFileStorageService {

    private OSSClient client;

    StorageAliyunCloudService(FileStorageConfig config) {
        this.config = config;
        //初始化
        init();
    }

    private void init() {
        CredentialsProvider credsProvider = new DefaultCredentialProvider(config.getAliyunAccessKeyId(), config.getAliyunAccessKeySecret());
        ClientConfiguration configuration = new ClientConfiguration();
        client = new OSSClient(config.getAliyunEndPoint(), credsProvider, configuration);
    }

    @Override
    protected String separator() {
        return PATH_SEPARATOR;
    }

    @Override
    protected String getPrefix() {
        return config.getAliyunPrefix();
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        PutObjectResult result;
        try {
            result = client.putObject(config.getAliyunBucketName(), path, inputStream);
        } catch (java.lang.Exception e) {
            throw new ServiceException("上传文件失败，请检查配置信息", e);
        } finally {
            // 关闭OSSClient。
            client.shutdown();
        }
        String uri = result.getResponse().getUri();
        if (log.isDebugEnabled()) {
            log.debug("上传文件:[{}]",uri);
        }
        String host = getOssHost();
        return host + path.replace("\\", PATH_SEPARATOR);
    }

    @Override
    public void download(String path, OutputStream out) {
        String finalPath = getOssObjectKey(path);
        OSSObject ossObject = client.getObject(config.getAliyunBucketName(), finalPath);
        try {
            InputStream in = ossObject.getObjectContent();
            //通知浏览器以附件形式下载
            //BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(new File("f:\\a.txt")));
            writeStream(in, out);
        } finally {
            client.shutdown();
        }
    }

    @Override
    public void delete(String path) {
        path = getOssObjectKey(path);
        // 删除文件。
        client.deleteObject(config.getAliyunBucketName(), path);
        // 关闭OSSClient。
        client.shutdown();
    }

    private String getOssObjectKey(String path) {
        String host = getOssHost();
        path = path.substring(host.length());
        return path;
    }

    private String getOssHost() {
        String host = "https://" + config.getAliyunBucketName() + ".";
        //在私有读时，如果有自定义域名，则添加自定义域名
        if (null != config.getAliyunDomain() && StringUtils.isNotBlank(config.getAliyunDomain())) {
            //待确定自定义域名时，是否要加 AliyunBucketName
            host += config.getAliyunDomain().replace("http://", "").replace("https://", "");
        } else {
            host += config.getAliyunEndPoint().replace("http://", "").replace("https://", "");
        }
        if (!host.endsWith(PATH_SEPARATOR)) {
            host += PATH_SEPARATOR;
        }
        return host;
    }
}
